<?php

include 'Zend/Http/Client.php';
include 'Zend/Json.php';
include 'Zend/Http/Client/Adapter/Exception.php';

class Kateglo
{
    const URLAPIKATEGLO = 'http://kateglo.com/api.php';
    
    protected $pdo;
    
    public function __construct(\PDO $pdo = null)
    {
        if ($pdo == null) {
            $dsn      = 'mysql:dbname=qas_quran; host=localhost; port=3306';
            $username = 'root';
            $password = 'kosong';
            $options  = array(
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            ); 

            try {
                $pdo  = new \PDO($dsn, $username, $password, $options);
                $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
                $this->pdo = $pdo;
            } catch (\PDOException $e) {
                ?>
                <div class="row">
                    <div class="col-lg-12">
                        <h1 class="page-header">ERROR</h1>
                    </div>
                </div>
                <?php
                echo '<div class="alert alert-danger">Connection failed : ' . $e->getMessage().'</div>';
                exit;
            }
        } else {
            $this->pdo = $pdo;
        }
    }
    
    public function getApiKatgelo($kata)
    {
        $client = new \Zend_Http_Client();
        $client->setUri(self::URLAPIKATEGLO);
        $client->setConfig(
            array(
                'maxredirects' => 0,
                'timeout'      => 120
            )
        );
        $client->setMethod(\Zend_Http_Client::GET);

        $client->setParameterGet(
            array(
                'format'  => 'json',
                'phrase'    => $kata,
            )
        );
        try {
            $respons = $client->request();
            $body    = $respons->getBody();
            $data    = \Zend_Json::decode($body);

            return $data;
        } catch (\Zend_Http_Client_Adapter_Exception $e) {
            return;
        } catch (\Exception $e) {
            return;
        }
    }
    
    public function getLexClassNameAndSinonims($kata)
    {
        $result = array();
        
        $kateglo = $this->getApiKatgelo($kata);
        $lexClassName = null;
        if (isset($kateglo['kateglo']['lex_class_name'])) {
            $lexClassName = $kateglo['kateglo']['lex_class_name'];
        }
        $result['lexClassName'] = $lexClassName;
        
        $sinonims = array();
        if (isset($kateglo['kateglo']['relation']['s'])) {
            foreach($kateglo['kateglo']['relation']['s'] as $key => $sinonim){
                if (isset($sinonim['related_phrase'])) {
                    if (!$this->lebih2Kata($sinonim['related_phrase'])) {
                        $sinonims[$sinonim['related_phrase']]['sinonim'] = $sinonim['related_phrase'];
                        $sinonims[$sinonim['related_phrase']]['lexClass'] = $sinonim['lex_class'];
                    }
                }
            }
        }
        $result['sinonims'] = $sinonims;
        return $result;
    }
    
    public function getLexClassName($kata)
    {
        $kateglo = $this->getApiKatgelo($kata);
        $lexClassName = null;
        if (isset($kateglo['kateglo']['lex_class_name'])) {
            $lexClassName = $kateglo['kateglo']['lex_class_name'];
        }
        return $lexClassName;
    }
    
    public function getLexClassRef($kata)
    {
        $kateglo = $this->getApiKatgelo($kata);
        $lexClassRef = null;
        if (isset($kateglo['kateglo']['lex_class_ref'])) {
            $lexClassRef = $kateglo['kateglo']['lex_class_ref'];
        }
        return $lexClassRef;
    }
    
    public function getSinonims($kata)
    {
        $kateglo = $this->getApiKatgelo($kata);
        $sinonims = array();
        if (isset($kateglo['kateglo']['relation']['s'])) {
            foreach($kateglo['kateglo']['relation']['s'] as $key => $sinonim){
                if (isset($sinonim['related_phrase'])) {
                    if (!$this->lebih2Kata($sinonim['related_phrase'])) {
                        $sinonims[$sinonim['related_phrase']]['sinonim'] = $sinonim['related_phrase'];
                        $sinonims[$sinonim['related_phrase']]['lexClass'] = $sinonim['lex_class'];
                    }
                }
            }
        }
        return $sinonims;
    }
    
    protected function lebih2Kata($phrase)
    {
        $lebih2Kata = false;
        $kata = explode(" ", $phrase);
        if (count($kata) > 1) {
            $lebih2Kata = true;
        }
        return $lebih2Kata;
    }
    
    public function insertNewKataDasar()
    {
        $fh = fopen('/var/www/qas-quran/vendor/sastrawi/sastrawi/data/kata-dasar.txt','r');
        $no = 1;
        while ($line = fgets($fh)) {
            echo $no.'. '.$line.'<br/>';
            //~ $sql = "INSERT INTO `kata_dasar` (kata) VALUES (:kata)";
            //~ $q   = $this->pdo->prepare($sql);
            //~ $q->execute(
                //~ array(
                    //~ ':kata'              => strtolower(trim($line))
                //~ )
            //~ );
            $no++;
        }
        fclose($fh);
    }
    
    public function updateNewKataDasar()
    {
        $sql = "SELECT * FROM `kata_dasar` WHERE tipe = '' ORDER BY kata DESC LIMIT 0,50";
        $no = 1;
        foreach ($this->pdo->query($sql) as $row) {
            $dataKateglo = $this->getLexClassNameAndSinonims($row['kata']);
            $jenisKata = '';
            if (isset($dataKateglo['lexClassName'])) {
                $jenisKata = strtolower($dataKateglo['lexClassName']);
            }
            
            $sql = "UPDATE `kata_dasar` SET `tipe`=? WHERE kata='".$row['kata']."'";
            $q = $this->pdo->prepare($sql);
            $q->execute(array($jenisKata));
            
            echo $no.'. '.$row['kata'].' - '.$jenisKata.'<br/>';
            $no++;
            sleep(1);
        }
    }
}

